import { Body, Controller, Post, Get, Req } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { ADMIN_PREFIX } from '../../admin.constants';
import { AdminUser } from '../../core/decorators/admin-user.decorator';

import { BaseMachineService } from './machine.service';
import { Authorize } from '../../core/decorators/authorize.decorator';
import { FastifyRequest } from 'fastify';

@ApiSecurity(ADMIN_PREFIX)
@ApiTags('设备管理模块')
@Controller('machine')
export class BaseMachineController {
  constructor(private baseMachineService: BaseMachineService) {}

  @ApiOperation({ summary: '获取设备列表' })
  @ApiOkResponse()
  @Get('list')
  async list() {
    return await this.baseMachineService.list();
  }

  @ApiOperation({ summary: '通过mac获取设备' })
  @ApiOkResponse()
  @Authorize()
  @Post('byMac')
  async getMachineByMac(@Body() dto) {
    return await this.baseMachineService.getMachineByMac(dto);
  }

  @ApiOperation({ summary: '分页获取获取设备列表' })
  @ApiOkResponse()
  @Post('page')
  async page(@Body() dto) {
    const [list, total] = await this.baseMachineService.page(dto);

    return {
      list,
      pagination: {
        total,
        pageNum: dto.pageNum,
        pageSize: dto.pageSize,
      },
    };
  }

  @ApiOperation({ summary: '添加设备' })
  @ApiOkResponse()
  @Post('add')
  async add(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;

    await this.baseMachineService.isExistKey(dto.machineCode);

    await await this.baseMachineService.isExistMac(dto);

    await await this.baseMachineService.isExistIp(dto);

    await this.baseMachineService.add(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '更新设备' })
  @ApiOkResponse()
  @Post('update')
  async update(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;

    await await this.baseMachineService.isExistMac(dto);

    await this.baseMachineService.update(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '删除设备' })
  @ApiOkResponse()
  @Post('delete')
  async delete(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;

    await this.baseMachineService.delete(dto, user, mac, ip, syncHostSqlite);
  }
}
